package com.gxa.community.admin.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gxa.community.admin.config.JwtProperties;
import com.gxa.community.admin.mapper.user.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@PropertySource("classpath:jwt.properties")
public class JWTUtils {
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;

    //生成token
    public String createToken(String loginAct) {
        try {
            Date date = new Date(System.currentTimeMillis() + Long.parseLong(jwtProperties.getEXPIRE_TIME()));
            Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getSECRET());
            //jwt的header部分
            Map<String, Object> map = new HashMap<>();
            map.put("alg", "HS256");
            map.put("typ", "JWT");
            // 附带loginAct信息
            return JWT.create()
                    .withHeader(map)//jwt的header部分
                    .withClaim("loginAct", loginAct)//私有声明
                    .withExpiresAt(date)//过期时间
                    .withIssuedAt(new Date())//签发时间
                    .sign(algorithm);//签名
        } catch (Exception e) {
            return null;
        }
    }

    //验证token
    //校验token的有效性，1、token的header和payload是否没改过；2、没有过期
    public boolean verify(String token) {
        String loginAct = jwtUtils.getLoginAct(token);
//        String key = userMapper.selectUserKeyByLoginAct(loginAct);
        try {
            //解密
//            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build();
//            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获得token中的信息，无需secret解密也能获得
     */
    public String getLoginAct(String token) throws JWTDecodeException {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("loginAct").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    //获取token中的失效时间
    public long getExpireTime(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Date expiresAt = jwt.getExpiresAt();
            long expiresAtTime = expiresAt.getTime();
            return expiresAtTime;
        } catch (JWTDecodeException e) {
            return 0;
        }
    }


//    //解析token
//    public static Claims parseToken(String token){
//        Key key = new SecretKeySpec("salt".getBytes(),SignatureAlgorithm.HS512.getJcaName());//盐值
//        Claims claims = Jwts.parser()
//                    .setSigningKey(key)
//                    .parseClaimsJws(token)
//                    .getBody();
//        return claims;

//        System.out.println("用户id--->" + claims.getId());
//        System.out.println("用户名--->" + claims.getSubject());
//        System.out.println("签发时间--->" + new SimpleDateFormat("yyyy-MM-dd").format(claims.getIssuedAt()));
//        System.out.println("过期时间--->" + new SimpleDateFormat("yyyy-MM-dd").format(claims.getExpiration()));
//    }

//    public static void main(String[] args) {
//        long expireTime = JWTUtils.getExpireTime("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJs" +
//                "b2dpbkFjdCI6ImFkbWluIiwiZXhwIjoxNjU0NDkyMzMzLCJpYXQiOjE2NTQ0ODUxMz" +
//                "N9.Tv1jumS93T-PxC3VtEYihfgxH7sEHBpuqMkOusc9mPQ");
//        System.out.println(expireTime);
//    }


}
